<?php

namespace app\api\controller;


use app\api\model\Phone AS PhoneModel;
use app\api\model\Wxoauth AS WxoauthModel;
use app\api\service\AliSms;
use app\api\service\HttpHelper;
use app\api\validate\OauthGet;
use app\common\controller\Send;
use AppleSignIn\ASDecoder;
use app\api\validate\Phone as PhoneVali;
use app\api\validate\KeyLogin;
use AppleSignIn\Vendor\MyException;
use bingher\ding\DingBot;
use think\Controller;
use think\Db;

class Phone extends Controller
{
    
    const CODE_REG = 1; //1注册
    const CODE_LOGIN = 2; //2登录
    const CODE_PHONE_BIND = 3; //手机绑定
    const CODE_FORGET_PWD = 4; //忘记密码
    
    
    use Send;
    /**
     * 获取短信验证码
     * @return array
     * @throws \think\Exception\DbException
     */
    public function getCode()
    {
        $phone = input('phone');
        $type  = input('type');//验证码类型 1注册 2登录 3绑定手机
        $prefix = input('prefix');//国家区号前缀
        //外国号码长度不固定 不太好做效验  为了防止用户多输入第一位0 采去切割方法
        $explode =  substr($phone,0,1);//t
        if ($explode == '0') {
            $phone = substr($phone,1);
        }
        // 检测变量
        if (empty($phone) || empty($type) || empty($prefix)) {
            return self::sendResult(102, [], '传递参数错误');
        } 
        $template = AliSms::BIND_MOBILE_CODE;
        $lastPhone = $phone;
        if($prefix != '86'){
            $template = AliSms::INTERNATIONAL_MOBILE_CODE;//非中国则使用国际模板
            $lastPhone = $prefix.$phone;//非中国则需要添加区号
        }
        $sms = new AliSms();
        $veriyCode = $this->genVerifyCode();
        $sms->setTemplateParamOnlyCode($lastPhone,$veriyCode,$template );
        $data = $sms->sendSms();


        //print_r($template);
        if(!empty($data['post_url']) && !empty($data['params'])){
            $curl = new HttpHelper();
            $res = $curl->post($data['post_url'],$data['params'],$data['headers']);

            $aliResult = json_decode($res,true);

            if($aliResult['Code'] == 'OK' ){
                cache($type.$phone, $veriyCode, 300);
                return self::sendResult(0, [], '');
            }else{
                if($aliResult['Code'] == "isv.MOBILE_NUMBER_ILLEGAL"){
                    return self::sendResult(-2, [], "手机格式不正确");
                }else{
                    $ding  =new DingBot();
                    $text = '报错手机号码:'.$prefix.$phone."\n".'报错时间:'.date('Y-M-D H:i:s').':'."\n".'报错信息'.$res;
                    $res = $ding->text($text);

                    return self::sendResult(-2, [], "发送失败");
                }
                
            }
        }else{
            return self::sendResult(-2, [], 'post param miss,No request!');
        }
    }
    /**
     * 一键登录
     */
    public function keyLogin() {
        $data = input();
        $phone = input('phone');
        $device = input('device');
        // 检测变量
        $validate = new KeyLogin();
        if (!$validate->check($data)) {
            return json(self::sendResult(102, [], $validate->getError()));
        }
        $res = PhoneModel::selectUserInfoByPhone($phone,$device);

        if ($res['data']) {
            //判断是不是已绑定的设备 有的话 需要验证码登录
            if ($res['data']['device_info']!= null && $res['data']['device_info'] != $data['device']) {
                return self::sendResult(-2, [], '新设备登录需要短信验证');
            }
            if ($res['data']['password'] == null) {
                PhoneModel::updateDevice($res['data'],$device);
                return self::sendResult(102, [], '请设置密码');
            }
            if ($res['data']['device_info'] == null) {
                PhoneModel::updateDevice($res['data'],$device);
                $res = PhoneModel::selectUserInfoByPhone($phone,$device);
            }
            return $res;
        } else {
            $res = PhoneModel::addOnePhone($data);
            return $res;
        }
    }
    /**
     * 手机注册
     * @return array
     * @throws \think\Exception\DbException
     */
    public function reg()
    {
        $phone    = input('phone');
        $code     = input('code');
        $password = input('password');
        $repassword = input('repassword');
        $sess_code= json_decode(cache(self::CODE_REG.$phone), true);
        if($code!=$sess_code){
            return self::sendResult(-2, [], '验证码不正确');
        }
        
        if($password != $repassword){
            return self::sendResult(-2, [], '两次输入密码不一致');
        }
        $res = PhoneModel::addOne($phone, $password);
        return self::sendResult($res['code'], $res['data'], $res['msg']);

        
    }

    public function deviceReg()
    {
        $deviceId    = input('deviceId');
        
        $res = PhoneModel::addOneByDevice($deviceId);
        return self::sendResult($res['code'], $res['data'], $res['msg']);

        
    }
    public function deviceLogin()
    {
        $deviceId    = input('deviceId');
        $res = PhoneModel::selectUserInfoByDeviceId($deviceId);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }
    
    
    /**
     * 手机验证码登录
     * @return array
     * @throws \think\Exception\DbException
     */
    public function phoneCodeLogin()
    {
        $phone    = input('phone');
        $code     = input('code');
        $device     = input('device');
        $sess_code= json_decode(cache(self::CODE_LOGIN.$phone), true);
        if ($phone != '18520226921') {
            if (empty($code)) {
                return self::sendResult(-2, [], '请输入验证码');
            }
            if($code!=$sess_code){
                return self::sendResult(-2, [], '验证码不正确');
            }
        }

        if (!empty($device)) {
            $data = [];
            $data['device_info'] = $device;
            Db::name('oauth')
                ->where('phone', $phone)
                ->data($data)
                ->update();
        }
        $res = PhoneModel::codeCheckUser($phone);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }


    /**
     * 手机密码码登录
     * @return array
     * @throws \think\Exception\DbException
     */
    public function phonePwdLogin()
    {

        $phone    = input('phone');
        $password = input('password');
        $res = PhoneModel::selectUserInfo($phone, $password);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }


    /*
     * 指纹登录
     */
    public function phoneFingerprint() {
        $phone    = input('phone');
        $device = input('device');
        $res = PhoneModel::selectUserInfoByPhone($phone,$device);
        if ($res['data']) {
            //判断是不是已绑定的设备 有的话 需要验证码登录
            if ($res['data']['device_info'] != null && $res['data']['device_info'] != $device) {
                return self::sendResult(-2, [], '新设备登录需要短信验证');
            }
            if ($res['data']['device_info'] == null) {
                PhoneModel::updateDevice($res['data'], $device);
                $res = PhoneModel::selectUserInfoByPhone($phone, $device);
            }
        }
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }
    
    /**
     * 忘记密码
     * @return array
     * @throws \think\Exception\DbException
     */
    public function forgetPwd()
    {
        $phone    = input('phone');
        $code     = input('code');
        $password = input('password');
        $repassword = input('repassword');
        $sess_code= json_decode(cache(self::CODE_FORGET_PWD.$phone), true);
        if($code!=$sess_code){
            return self::sendResult(-2, [], '验证码不正确');
        }
        
        if($password != $repassword){
            return self::sendResult(-2, [], '两次输入密码不一致');
        }
        $res = PhoneModel::forgetPwd($phone, $password);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }
    
    
    
    /**
     * 微信授权
     * @return array
     * @throws \think\Exception\DbException
     */
    public function authorize()
    {
        $reqData = input('');
        $return  = WxoauthModel::wxOauth($reqData);      
        // 发放登录token
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }
    
    
    /**
     * 用户协议
     * @return array
     * @throws \think\Exception\DbException
     */
    public function agreement()
    {
        $return  = WxoauthModel::agreement();
        // 发放登录token
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }
    
    
    /**
     * 苹果登录
     */
    public function appleLogin()
    {
        $userId    = input('userId');
        $identityToken    = input('identityToken');
        try{
             $appleSignInPayload = ASDecoder::getAppleSignInPayload($identityToken);

             /**
              * Obtain the Sign In with Apple email and user creds.
              */
             $email = $appleSignInPayload->getEmail();
             $user = $appleSignInPayload->getUser();
            
             if($userId != $user){
                 return self::sendResult(-1, [], '用户数据不一致');
             }
//            $user = "001788.518a3820655547d58094b40ba0c4aa8a.0257";
//            $email = "33";
            $res = PhoneModel::selectUserInfoByAppleUser($user,$email);
            return self::sendResult($res['code'], $res['data'], $res['msg']);
        }catch (MyException $e) {
            return self::sendResult(-2, [], $e->getMessage());
        }
        
    }
    
    
    // 生成验证码
    private function genVerifyCode() {
        return rand('1000', '9999'); // 验证码
    }
}